#!/bin/bash
set -eu

check_char='\xE2\x9C\x93'
cross_char='\xE2\x9D\x8C'
green='\033[0;32m'
red='\033[0;31m'
nc='\033[0m'
check="$green$check_char$nc"
cross="$red$cross_char$nc"
errors=0


## Require_clean_work_tree ##
# Update the index
git update-index -q --ignore-submodules --refresh
err=0

# Disallow unstaged changes in the working tree
if ! git diff-files --quiet --ignore-submodules --
then
    echo -e "you have unstaged changes. $cross"
    git diff-files --name-status -r --ignore-submodules -- >&2
    err=1
fi

# Disallow uncommitted changes in the index
if ! git diff-index --cached --quiet HEAD --ignore-submodules --
then
    echo -e "your index contains uncommitted changes. $cross"
    git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2
    err=1
fi

if [ $err = 1 ]
then
    echo -e "Please commit or stash them."
    exit 1
fi

: '
echo -n "Checking formatting... "
diff=$(cargo fmt -- --write-mode diff)
stripped_diff=$(echo "$diff" | sed -e '/^Diff of/d' -e '/^$/d')

if [ -z "$stripped_diff" ]; then
	echo -e "$check"
else
	echo -e "$cross"
	echo "$diff"
	errors=1
fi
'

echo -n "Running tests... "
if result=$(cargo +nightly test --color always 2>&1); then
	echo -e "$check"
else
	echo -e "$cross"
	echo "$result"
	errors=1
fi

echo -n "Compiling benchmarks... "
if result=$(cargo +nightly check --bench basic --color always 2>&1); then
	echo -e "$check"
else
	echo -e "$cross"
	echo "$result"
	errors=1
fi


if [ "$errors" != 0 ]; then
	echo "Failed"
	exit 1
else
	echo "OK"
fi
